package com.kandinfo.survey.common.service.impl;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kandinfo.base.common.converter.ConverterService;
import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;
import com.kandinfo.base.common.service.AbstractService;
import com.kandinfo.survey.common.domain.Question;
import com.kandinfo.survey.common.dto.QuestionDto;
import com.kandinfo.survey.common.mongo.QcQuestionDto;
import com.kandinfo.survey.common.repository.QuestionOptionRepository;
import com.kandinfo.survey.common.repository.QuestionRepository;
import com.kandinfo.survey.common.service.MongoQuestionService;
import com.kandinfo.survey.common.service.QuestionService;

@Service
public class QuestionServiceImpl extends AbstractService<Question, Long, QuestionRepository> implements QuestionService {

    private static final Logger logger = LoggerFactory.getLogger(QuestionServiceImpl.class);
    
    @Autowired
    QuestionOptionRepository questionOptionRepository;
    @Autowired
    MongoQuestionService mongoQuestionService;
    
    @Resource
    public void setQuestionRepository(QuestionRepository questionRepository) {
        super.setRepository(questionRepository);
    }

    @Override
    @Transactional
    public ResultDto newQuestion(QuestionDto questionDto) {
        if (questionDto == null) {
            return ResultDtoFactory.toNack(" 参数不能为空! ", Boolean.FALSE);
        }
        // mysql question
        saveQuestion(questionDto);
        // save mongo
        saveMongo(questionDto);
        
        // FIXME
        return ResultDtoFactory.toAck("题目创建成功! ", Boolean.TRUE);
    }
    
    private void saveQuestion(QuestionDto questionDto) {
        Question question = new Question();
        try {
            question = ConverterService.convert(questionDto, Question.class);
            
            repository.save(question);
        } catch (Exception e) {
            logger.error(" newQuestion convert error - QuestionServiceImpl - save question ", e.toString());
        }
    }
    
    private void saveMongo(QuestionDto questionDto) {
        QcQuestionDto mongoDto = new QcQuestionDto();
        // FIXME
        // 组织结构未添加
        try {
            mongoDto = ConverterService.convert(questionDto, QcQuestionDto.class);
            mongoQuestionService.save(mongoDto);
        } catch (Exception e) {
            logger.error(" newQuestion convert error - QuestionServiceImpl - saveMongo ", e.toString());
        }
    }
}
